package com.ludomancy.breathe;

import java.io.InputStream;
import java.util.Hashtable;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class PsycheLoader extends DefaultHandler
{
	private PsycheGraph construct = null;
	
	private PsycheLoader()
	{
		construct = new PsycheGraph();
	}
	
	public static PsycheGraph load()
	{
		PsycheLoader pl = new PsycheLoader();
		try
		{
			InputStream is = BreatheApp.app.getClass().getResourceAsStream("/bruno.xml");
			SAXParserFactory factory = SAXParserFactory.newInstance();
			SAXParser parser = factory.newSAXParser();
			parser.parse(is, pl);
			is.close();
		}
		catch(Exception e)
		{
		}
		return pl.construct;
	}
	
	private String nodeID;
	private String nodeDesc;
	private double intensity;
	private String relationNode1;
	private String relationNode2;
	private double relationWeight;
	private Hashtable nodes = new Hashtable();

	public void startElement(String uri, String localName, String qName, Attributes attr) throws SAXException
	{
		if(qName.equals("node"))
		{
			nodeID = attr.getValue("id");
			intensity = Double.parseDouble(attr.getValue("threat"));
		}
		else
		if(qName.equals("rel"))
		{
			relationNode1 = attr.getValue("p1");
			relationNode2 = attr.getValue("p2");
			relationWeight = Double.parseDouble(attr.getValue("w"));
		}
	}

	public void characters(char[] ch, int start, int length) throws SAXException
	{
		if(nodeID != null)
		{
			String entry = new String(ch, start, length);
			entry = entry.trim();
			nodeDesc = entry;
		}
	}

	public void endElement(String uri, String localName, String qName) throws SAXException
	{
		if(nodeID != null)
		{
			PsycheNode newNode = new PsycheNode(nodeID, nodeDesc, intensity);
			construct.addVertex(newNode);
			nodes.put(nodeID, newNode);
		}
		else
		if(relationNode1 != null)
		{
			construct.addEdge((PsycheNode) nodes.get(relationNode1), (PsycheNode) nodes.get(relationNode2), relationWeight);
		}
		
		nodeID = null;
		nodeDesc = null;
		relationNode1 = null;
		relationNode2 = null;
	}
}
